import React, {
    useState,
    useEffect,
    ReactNode,
    MouseEventHandler,
} from 'react';
import {
    PageHeader,
    Form,
    Input,
    Radio,
    Typography,
    Tag,
    Spin,
    Select,
    AutoComplete,
} from 'antd';
import { WingBlank, WhiteSpace } from 'antd-mobile';
import FormItemLabel from '../order_detail/components/FormItemLabel';
import { DatePicker, Button, ImagePicker } from 'antd-mobile';
import { requestAllComponays } from './server';
import { IComponay } from './data';
import { getPageQuery } from '@/utils';
import moment from 'moment';

import {
    ConnectProps,
    connect,
    UserModelState,
    OrderModelState,
    Loading,
} from 'umi';

interface OrderNewProps extends ConnectProps {
    user: UserModelState;
    location: any;
    history: any;
    order: OrderModelState;
    loading: boolean;
}

const CustomChildren = ({
    extra,
    onClick,
    children,
}: {
    extra?: ReactNode;
    onClick?: MouseEventHandler<HTMLDivElement>;
    children?: ReactNode;
}) => (
    <div
        onClick={onClick}
        style={{
            backgroundColor: '#fff',
        }}
    >
        {children}
        <span style={{ textAlign: 'center', color: '#888' }}>{extra}</span>
    </div>
);

const { Title } = Typography;
const { TextArea } = Input;
const NewOrder: React.FC<OrderNewProps> = ({
    user,
    loading,
    history,
    order,
    dispatch,
}) => {
    const [form] = Form.useForm();
    // State
    const [companays, setCompanays] = useState<IComponay[]>([]);
    const [orderid, setOrderid] = useState<any>(undefined);
    const [companyOptions, setCompanyOptions] = useState<{ value: string }[]>(
        [],
    );
    // Effect
    useEffect(() => {
        if (order.id) {
            setOrderid(order.id);
        }
        if (dispatch && order.id) {
            dispatch({
                type: 'order/query',
                payload: {
                    userinfo: {
                        token: user.token,
                        userid: user.userid,
                    },
                    request: {
                        id: order.id,
                    },
                },
            });
        }
        requestAllComponays({
            userInfo: {
                token: user.token,
                userid: user.userid,
            },
            request: {},
        }).then(res => {
            if (res.status === 0) {
                //  过滤 null 公司
                const companysFilter = res.data.filter(
                    (i: any) => i.company && i.companyid,
                );
                setCompanays(companysFilter);
                setCompanyOptions(
                    companysFilter.map((i: any) => {
                        if (i.company) {
                            return { value: i.company };
                        }
                    }),
                );
            }
        });
    }, []);
    // Event
    const handleFormFinish = (values: any) => {
        function getCompanyId(v: string) {
            const t = companays.filter(i => i.company === v);
            return t[0].companyid;
        }
        if (dispatch) {
            dispatch({
                type: 'order/post',
                payload: {
                    userInfo: {
                        token: user.token,
                        userid: user.userid,
                    },
                    request: {
                        ...values,
                        id: order.id,
                        companyId: getCompanyId(values.company),
                        notice_time: moment(values.notice_time).format(
                            'YYYY-MM-DD HH:mm',
                        ),
                        estimated_finish_time: moment(
                            values.estimated_finish_time,
                        ).format('YYYY-MM-DD HH:mm'),
                        service_time: moment(values.service_time).format(
                            'YYYY-MM-DD HH:mm',
                        ),
                        finishImages: values.finishImages.map(
                            (i: any) => i.url,
                        ),
                    },
                },
            });
        }
    };
    const handleComponayChange = (values: any) => {
        const t = companays.filter(i => i.company === values);
        form.setFieldsValue({
            personofrepair: t[0].name,
            phone: t[0].phone,
        });
    };
    return (
        <>
            {loading && (
                <Spin
                    style={{
                        position: 'fixed',
                        left: '50%',
                        top: '50%',
                        transform: 'translate(-50%, -50%)',
                    }}
                />
            )}
            {!loading && companays.length > 0 && (
                <>
                    <PageHeader
                        title={orderid ? '修改订单' : '创建新订单'}
                        onBack={() => {
                            history.goBack();
                        }}
                    />
                    <WingBlank size="lg">
                        <WhiteSpace size="lg" />
                        <Form
                            form={form}
                            onFinish={handleFormFinish}
                            initialValues={
                                orderid
                                    ? {
                                          ...order,
                                          notice_time: order.notice_time
                                              ? new Date(order.notice_time)
                                              : new Date(),
                                          estimated_finish_time: order.estimated_finish_time
                                              ? new Date(
                                                    order.estimated_finish_time,
                                                )
                                              : new Date(),
                                          service_time: order.service_time
                                              ? new Date(order.service_time)
                                              : new Date(),
                                          completedTime: order.completedTime
                                              ? new Date(order.completedTime)
                                              : new Date(),
                                          finishImages: order.finishImages.map(
                                              (i, s) => ({ url: i, id: s }),
                                          ),
                                      }
                                    : {
                                          finishImages: [],
                                      }
                            }
                        >
                            <Title level={4} className="blue-text">
                                业主信息
                            </Title>
                            <Form.Item
                                name="company"
                                label={
                                    <FormItemLabel
                                        content="维修单位:"
                                        icon="#icon-danwei"
                                        required
                                    />
                                }
                                className="inline"
                                rules={[
                                    {
                                        required: true,
                                        message: '请选择或者输入维修单位',
                                    },
                                ]}
                            >
                                <AutoComplete
                                    options={companyOptions}
                                    onSelect={handleComponayChange}
                                    filterOption={(inputValue, option) =>
                                        option.value.indexOf(inputValue) !== -1
                                    }
                                />
                            </Form.Item>
                            <Form.Item
                                name="personofrepair"
                                label={
                                    <FormItemLabel
                                        content="通知维修人:"
                                        icon="#icon-shuidiangong"
                                    />
                                }
                                className="inline"
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                name="phone"
                                label={
                                    <FormItemLabel
                                        content="联系电话:"
                                        icon="#icon-weibiaoti-"
                                    />
                                }
                                className="inline"
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                name="notice_time"
                                label={
                                    <FormItemLabel
                                        content="通知时间:"
                                        icon="#icon-shijian"
                                    />
                                }
                                className="inline"
                            >
                                <DatePicker mode="datetime">
                                    <CustomChildren></CustomChildren>
                                </DatePicker>
                            </Form.Item>
                            <Form.Item
                                name="crash"
                                label={
                                    <FormItemLabel
                                        content="紧急程度:"
                                        icon="#icon-jinjichengdu-"
                                        required
                                    />
                                }
                                className="inline"
                            >
                                <Radio.Group>
                                    <Radio value={1}>一般</Radio>
                                    <Radio value={2}>急</Radio>
                                    <Radio value={3}>加急</Radio>
                                </Radio.Group>
                            </Form.Item>
                            <Form.Item
                                name="content"
                                label={
                                    <FormItemLabel
                                        content="维修内容:"
                                        icon="#icon-neirong"
                                        required
                                    />
                                }
                            >
                                <TextArea />
                            </Form.Item>
                            <Form.Item
                                name="completedTime"
                                label={
                                    <FormItemLabel
                                        content="要求完成时间:"
                                        icon="#icon-shijian"
                                    />
                                }
                                className="inline border_bottom_line"
                            >
                                <DatePicker mode="datetime">
                                    <CustomChildren></CustomChildren>
                                </DatePicker>
                            </Form.Item>
                            <Title
                                className="blue-text"
                                level={4}
                                style={{ margin: '20px 0' }}
                            >
                                服务信息
                            </Title>
                            <Form.Item
                                name="status"
                                label={
                                    <FormItemLabel
                                        content="维修结果:"
                                        icon="#icon-z-like"
                                        required
                                    />
                                }
                                className="inline"
                            >
                                <Radio.Group
                                    style={{ display: 'flex' }}
                                    buttonStyle="solid"
                                >
                                    <Radio.Button
                                        value={3}
                                        style={{ fontSize: '12px' }}
                                    >
                                        维修中
                                    </Radio.Button>
                                    <Radio.Button
                                        value={4}
                                        style={{ fontSize: '12px' }}
                                    >
                                        已完成
                                    </Radio.Button>
                                    <Radio.Button
                                        value={5}
                                        style={{ fontSize: '12px' }}
                                    >
                                        未完成
                                    </Radio.Button>
                                </Radio.Group>
                            </Form.Item>
                            <Form.Item
                                name="estimated_finish_time"
                                label={
                                    <FormItemLabel
                                        content="预定完成时间:"
                                        icon="#icon-shijian"
                                    />
                                }
                                className="inline"
                            >
                                <DatePicker mode="datetime">
                                    <CustomChildren></CustomChildren>
                                </DatePicker>
                            </Form.Item>
                            <Form.Item
                                name="service_time"
                                label={
                                    <FormItemLabel
                                        content="服务时间:"
                                        icon="#icon-shijian"
                                        required
                                    />
                                }
                                className="inline"
                            >
                                <DatePicker mode="datetime">
                                    <CustomChildren></CustomChildren>
                                </DatePicker>
                            </Form.Item>
                            <Form.Item
                                name="incompleteReason"
                                label={
                                    <FormItemLabel
                                        content="未完成原因:"
                                        icon="#icon-shibaiyuanyin"
                                    />
                                }
                                className="inline"
                            >
                                <Input />
                            </Form.Item>
                            <Form.Item
                                name="finishImages"
                                label={
                                    <FormItemLabel
                                        content="服务完成照片:"
                                        icon="#icon-zhaopian"
                                    />
                                }
                                className="inline"
                                valuePropName="files"
                            >
                                <ImagePicker multiple />
                            </Form.Item>
                        </Form>
                        <Button
                            onClick={() => form.submit()}
                            style={{ marginTop: '10px' }}
                            type="primary"
                            loading={loading}
                        >
                            提交
                        </Button>
                        <Button
                            onClick={() => form.resetFields()}
                            style={{ marginTop: '10px' }}
                            type="warning"
                        >
                            重置
                        </Button>
                        <WhiteSpace size="lg" />
                    </WingBlank>
                </>
            )}
        </>
    );
};
export default connect(
    ({
        user,
        order,
        loading,
    }: {
        user: UserModelState;
        order: OrderModelState;
        loading: Loading;
    }) => ({
        user,
        order,
        loading: loading.models.order,
    }),
)(NewOrder);
